using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CrystalControler : MonoBehaviour
{
    private float crystalExistTimer;
    private bool canExplode;
    private bool canMoveToEnemy;
    private Player player;
    private float moveSpeed;
    private bool canGrow;
    private Transform closestEnemy;
    [SerializeField]private float growSpeed;

    private CircleCollider2D cd=>GetComponent<CircleCollider2D>();
    private Animator anim=>GetComponent<Animator>();
    public void SetUpCrystal(float _crystalDuration,bool _canMoveToEnemy,float _moveSpeed,bool _canExplode,Transform _closestEnemy,Player _player)
    {
        player = _player;
        crystalExistTimer = _crystalDuration;
        canExplode = _canExplode;
        closestEnemy = _closestEnemy;
        canMoveToEnemy = _canMoveToEnemy;
        moveSpeed = _moveSpeed;
    }
    private void Update()
    {
        crystalExistTimer-= Time.deltaTime;
        if(crystalExistTimer < 0)
        {
            FinishCrystal();
        }
        if (canGrow)
        {
            transform.localScale = Vector2.Lerp(transform.localScale, new Vector2(4, 4), growSpeed * Time.deltaTime);
        }
        if (canMoveToEnemy)
        {
            transform.position = Vector2.MoveTowards(transform.position, closestEnemy.position, moveSpeed * Time.deltaTime);
            if (Vector2.Distance(transform.position, closestEnemy.position) < 1)
            {
                FinishCrystal();
            }
        }
        
    }

    public void FinishCrystal()
    {
        if (canExplode)
        {
            canGrow = true;
            canMoveToEnemy= false;
            anim.SetTrigger("Explode");
        }
         else SelfDestory();
    }

    public void SelfDestory() => Destroy(gameObject);
    public void SetCanExplode()
    {
        canExplode = false;
    }
    public void AnimationEvent()
    {
        Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, cd.radius);
        foreach (var hit in colliders)
        {
            if (hit.GetComponent<Enemy>() != null)
            {
                player.start.DoMagicalDamage(hit.GetComponent<CharacterStart>());


            }
        }
    }
}
